package com.amos.cmp_android.net;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.text.TextUtils;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.amos.cmp_android.SysApplication;
import com.amos.cmp_android.utils.VolleyUtil;

/**
 * 第三方网络访问的隔离，应用中网络访问方法统一使用此类提供的方法，在此类的方法实现中再调用第三方库实现网络访问。
 * 这样在更换第三方库时就只需更改此处的实现。
 */
public class STJsonQuery implements ISTNetWork{
	
	private STNetTask.BeforeQueryHook beforeQueryHook;
	private STNetTask.AfterQueryHook afterQueryHook;
	/**
	 * 向服务器提交JSON对象。
	 * request 在request中设置JSON数据
	 * 提交的是键值对时需要传入，若为json则为null
	 * callback
	 */
	@Override
	public void post(STRequest request, STHttpCallback<JSONObject> callback) {
		query(request.generateUrl(), request.getJson(), request.getParams(), callback);
	}
	
	/**
	 * 使用Volley实现的网络方法。
	 * url
	 * requestJson
	 * 提交的是键值对时需要传入，若为json则为null
	 * callback
	 */
	@Override
	public void query(String url, JSONObject requestJson,final Map<String, Object> params, final STHttpCallback<JSONObject> callback) {
		RequestQueue requestQueue = VolleyUtil.getRequestQueue();
		if(beforeQueryHook != null) {
			beforeQueryHook.beforeQueryHook();
		}
		
		Response.ErrorListener errorListener = new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub
				if(afterQueryHook != null) {
					afterQueryHook.afterQueryHook();
				}
				if(error.networkResponse != null) {
					callback.onFailed(new STError(error.networkResponse.statusCode, "网络错误"));
				} else {
					callback.onFailed(new STError(0, "连接超时，请检查您的网络"));
					
				}
			}
		};
		if(requestJson.length() != 0) {
			Listener<JSONObject> jsonListener = new Listener<JSONObject>() {
				@Override
				public void onResponse(JSONObject response) {
					// TODO Auto-generated method stub
					if(afterQueryHook != null) {
						afterQueryHook.afterQueryHook();
					}
					callback.onSuccess(response.toString());
				}
			};
			JsonObjectRequest request = new JsonObjectRequest(Method.POST, url, requestJson, jsonListener, errorListener) {
				@Override
			    public Map<String, String> getHeaders() {
			        HashMap<String, String> headers = new HashMap<String, String>();
			        headers.put("Accept", "application/json");
			        headers.put("Content-Type", "application/json; charset=UTF-8");
			                 
			        return headers;
			    }
			};
			requestQueue.add(request);
		} else {
			Listener<String> stringListener = new Listener<String>() {

				@Override
				public void onResponse(String response) {
					// TODO Auto-generated method stub
					if(afterQueryHook != null) {
						afterQueryHook.afterQueryHook();
					};
					callback.onSuccess(response);
						
				}
				
			};
			StringRequest stringRequest = new StringRequest(Method.POST, url,  stringListener, errorListener) {  
			    @Override  
			    protected Map<String, String> getParams() throws AuthFailureError {  
			    	if(params == null) return null;
			        Map<String, String> map = new HashMap<String, String>();  
			        for(Map.Entry<String, Object> entry : params.entrySet()) {
						map.put(entry.getKey(), String.valueOf(entry.getValue()));
					}  
			        return map;  
			    }  
			};
			requestQueue.add(stringRequest);
		}
	}

	@Override
	public void setBeforeQueryHook(STNetTask.BeforeQueryHook hook) {
		// TODO Auto-generated method stub
		this.beforeQueryHook = hook;
	}

	@Override
	public void setAfterQueryHook(STNetTask.AfterQueryHook hook) {
		// TODO Auto-generated method stub
		this.afterQueryHook = hook;
	}
	
	 
}
